package config

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"os"
	"path"
)

const (
	ENV_PROD = "prod"
	ENV_TEST = "test"
	ENV_DEV  = "dev"
)

var (
	environment string = ENV_DEV                                                                            // app允许环境
	basePath    string = "/Please set go app config directory path. environment variable name is CONF_PATH" // 配置文件基本路径, 当前文件目录
)

// 根据当前环境获取配置文件
func init() {
	var (
		confPath string = os.Getenv("CONF_PATH")
		confEnv  string = os.Getenv("CONF_ENV")
	)

	// 设置程序运行环境
	if confEnv != "" {
		environment = confEnv
	}

	// 设置配置文件路径
	if confPath != "" {
		basePath = confPath
	} else {
		setBasePathIfExists := func(path string) error {
			_, fErr := os.Stat(path)
			if fErr == nil {
				basePath = path
			}
			return fErr
		}
		if baseDir, err := os.Getwd(); err == nil {
			if fErr := setBasePathIfExists(path.Join(baseDir, "configs")); fErr != nil {
				if os.IsNotExist(fErr) {
					setBasePathIfExists(path.Join(baseDir, "config"))
				}
			}
		}
	}

}

// SetEnv 设置当前运行环境：prod test dev
func SetEnv(env string) {
	environment = env
}

// SetBasePath 设置 basepath
func SetBasePath(newPath string) {
	basePath = newPath
}

// GetBasePath 获取当前的 basepath
func GetBasePath() string {
	return basePath
}

// GetConfigPath 获取当前读取的配置文件目录
func GetConfigPath() string {
	return path.Join(basePath, environment)
}

// Get 通过文件名，读取配置文件
func Get(filename string, out interface{}) {
	file := fmt.Sprintf("%s/%s/%s.yaml", basePath, environment, filename)
	handle, err := os.OpenFile(file, os.O_RDWR, os.ModePerm)

	if nil != err {
		panic(err.Error())
	}

	defer handle.Close()
	data, _ := ioutil.ReadAll(handle)
	yaml.Unmarshal(data, out)
}

// Environment 获取或设置当前运行环境
func Environment(args ...string) string {
	if len(args) > 0 {
		environment = args[0]
	}

	return environment
}

func IsProdEnv() bool {
	return environment == ENV_PROD
}

func IsTestEnv() bool {
	return environment == ENV_TEST
}

func IsDevEnv() bool {
	return environment == ENV_DEV
}
